<template>
  <div>
    <BasicCard>
      <BasicVxeForm ref="formRef" :formOptions="formOptions" :clearable="false" @search="getData" />
    </BasicCard>

    <BasicCard>
      <BasicVxeTable v-bind="statisticsGridOptions"> </BasicVxeTable>
    </BasicCard>

    <BasicCard>
      <BasicVxeTable v-bind="statisticsByMaterialGridOptions"> </BasicVxeTable>
    </BasicCard>

    <BasicCard>
      <BasicVxeTable v-bind="detailGridOptions"> </BasicVxeTable>
    </BasicCard>
  </div>
</template>

<script setup lang="ts">
  import {
    getCurrentAndLastBanCi,
    getQuYuOptions,
    getListItem,
    splitTsIdToTime,
    convertTimeUnit,
    formatNumber,
    getGongXuJiTaiOptions
  } from '@/utils'
  import { calcFooter } from '@/components/ui/vxe-table'
  import { columns, sumFields } from './data'
  import { getJiChuBaoBiaoGongXu } from '@/api/gongGongChaXun'
  import { postJiTaiJiaoXiao, postJiTaiJiaoXiao_XS } from '../../../api/personAdmin'

  export interface FormV0 {
    quYuValue: string
    gongXuId: string
    tsIdSelect: ShiftSchedulePickerData
    equipmentList: string[]
  }

  const props = defineProps<{
    isQuYu: boolean
  }>()

  const { t } = useI18n()

  // 区域
  const quYuOptions = ref<LabelValueOption[]>([])
  // 工序
  const gongXuOptions = ref<LabelValueOption[]>([])
  // 班次
  const shiftOptions = ref<LabelValueOption[]>([])
  // 机台
  const equipmentOptions = ref<LabelValueOption[]>([])

  const showTablesLoading = () => {
    statisticsGridOptions.loading = true
    statisticsByMaterialGridOptions.loading = true
    detailGridOptions.loading = true
  }

  const hideTablesLoading = () => {
    statisticsGridOptions.loading = false
    statisticsByMaterialGridOptions.loading = false
    detailGridOptions.loading = false
  }

  const clearTablesData = () => {
    statisticsGridOptions.data = []
    statisticsByMaterialGridOptions.data = []
    detailGridOptions.data = []
  }

  // 获取工艺节点list
  const getGongXuBuDaiFuJi = async () => {
    await getJiChuBaoBiaoGongXu().then((res) => {
      gongXuOptions.value = res.map((v) => ({ ...v, label: v.name, value: v.id }))
      formOptions.data!.gongXuId =
        gongXuOptions.value.find((v) => v.label === '细纱')?.value || gongXuOptions.value[0].value
    })
  }

  // 获取tsIdSelect选择器的数据和选项
  const getTsIdSelect = async () => {
    const banCiOpt = await getCurrentAndLastBanCi(
      props.isQuYu ? formOptions.data!.quYuValue : formOptions.data!.gongXuId,
      { isQy: props.isQuYu, isGetLast: true }
    )

    formOptions.data!.tsIdSelect = banCiOpt.banCiInfo
    shiftOptions.value = banCiOpt.shiftOptions

    getData()
  }

  // 获取工序机台
  const getEquipmentList = async () => {
    const { gongXuId, quYuValue } = formOptions.data!
    // 获取工序机台
    equipmentOptions.value = await getGongXuJiTaiOptions(
      {
        craftNodeId: gongXuId,
        areaId: quYuValue
      },
      { isQy: props.isQuYu }
    )

    // 全选
    formOptions.data!.equipmentList = equipmentOptions.value.map((v) => v.value)
  }

  // 工序变化时
  const handleGongXuChange = async () => {
    const { gongXuId } = formOptions.data!
    const gongXuName = getListItem(gongXuOptions.value, gongXuId)?.label

    if (gongXuName) {
      showTablesLoading()
      clearTablesData()
      if (['细纱', '络筒', '末并'].includes(gongXuName)) {
        statisticsGridOptions.columns = columns[gongXuName]['equipment']['statisticsColumns']
        statisticsByMaterialGridOptions.columns =
          columns[gongXuName]['equipment']['statisticsByMaterialColumns']
        detailGridOptions.columns = columns[gongXuName]['equipment']['detailColumns']
      } else {
        statisticsGridOptions.columns = columns['default']['equipment']['statisticsColumns']
        statisticsByMaterialGridOptions.columns =
          columns['default']['equipment']['statisticsByMaterialColumns']
        detailGridOptions.columns = columns['default']['equipment']['detailColumns']
      }

      getEquipmentList()

      getTsIdSelect()
    }
  }

  const formatDate = (date?: string | number) => {
    return convertTimeUnit(date, 's', 'm')
  }

  // 获取员工绩效列表
  const getData = async () => {
    try {
      showTablesLoading()
      const { tsIdSelect, gongXuId, equipmentList } = formOptions.data!
      const { startTsId, endTsId } = tsIdSelect
      const gongXuName = getListItem(gongXuOptions.value, gongXuId)?.label

      let data = {
        tsIdStart: startTsId,
        tsIdEnd: endTsId,
        craftNodeName: gongXuName,
        machineDocumentIds: equipmentList
      }

      statisticsGridOptions.data = []
      statisticsByMaterialGridOptions.data = []
      detailGridOptions.data = []

      if (gongXuName === '细纱') {
        await postJiTaiJiaoXiao_XS(data).then((res) => {
          statisticsGridOptions.data = res.statistics.map((v) => ({
            ...v,
            breakCntToNext: formatNumber(v.breakCntToNext),
            jointTimeAvg: formatDate(v.jointTimeAvg),
            doffingTimeAvg: formatDate(v.doffingTimeAvg),
            efcRun: formatNumber(v.efcRun),
            yarnLength: formatNumber(v.yarnLength),
            // classLength: formatNumber(v.classLength, 0),
            actualYarnWeight: formatNumber(v.actualYarnWeight, 1),
            doffingCnt: formatNumber(v.doffingCnt, 0),
            stopTime: formatDate(v.stopTime),
            stopTimeAvg: formatDate(v.stopTimeAvg)
          }))

          statisticsByMaterialGridOptions.data = res.statisticsByMaterialMachine.map((v) => ({
            ...v,
            breakCntToNext: formatNumber(v.breakCntToNext),
            jointTimeAvg: formatDate(v.jointTimeAvg),
            doffingTimeAvg: formatDate(v.doffingTimeAvg),
            efcRun: formatNumber(v.efcRun),
            // classLength: formatNumber(v.classLength, 0),
            actualYarnWeight: formatNumber(v.actualYarnWeight, 1),
            doffingCnt: formatNumber(v.doffingCnt, 0),
            stopTime: formatDate(v.stopTime),
            stopTimeAvg: formatDate(v.stopTimeAvg),
            yarnLength: formatNumber(v.yarnLength)
          }))

          detailGridOptions.data = res.detail.map((v) => ({
            ...v,
            dateTimeStr: splitTsIdToTime(v.tsId) + v.shiftName,
            breakCntToNext: formatNumber(v.breakCntToNext),
            jointTimeAvg: formatDate(v.jointTimeAvg),
            doffingTimeAvg: formatDate(v.doffingTimeAvg),
            efcRun: formatNumber(v.efcRun),
            // classLength: formatNumber(v.classLength, 0),
            actualYarnWeight: formatNumber(v.actualYarnWeight, 1),
            doffingCnt: formatNumber(v.doffingCnt, 0),
            stopTime: formatDate(v.stopTime),
            stopTimeAvg: formatDate(v.stopTimeAvg),
            yarnLength: formatNumber(v.yarnLength)
          }))
        })
      } else {
        await postJiTaiJiaoXiao(data).then((res) => {
          statisticsGridOptions.data = res.statistics.map((v) => ({
            ...v,
            efcRun: formatNumber(v.efcRun),
            // classLength: formatNumber(v.classLength, 0),
            actualYarnWeight: formatNumber(v.actualYarnWeight, 1),
            // jointTimeRound: formatNumber(v.jointTimeRound, 0),
            stopTime: formatDate(v.stopTime),
            stopTimeAvg: formatDate(v.stopTimeAvg),
            warningCnt: v.warningCnt,
            durationTotal: formatNumber(convertTimeUnit(v.durationTotal, 'ms', 'm')),
            yarnLength: formatNumber(v.yarnLength)
          }))

          statisticsByMaterialGridOptions.data = res.statisticsByMaterialMachine.map((v) => ({
            ...v,
            efcRun: formatNumber(v.efcRun),
            // classLength: formatNumber(v.classLength, 0),
            actualYarnWeight: formatNumber(v.actualYarnWeight, 1),
            // jointTimeRound: formatNumber(v.jointTimeRound, 0),
            stopTime: formatDate(v.stopTime),
            stopTimeAvg: formatDate(v.stopTimeAvg),
            warningCnt: v.warningCnt,
            durationTotal: formatNumber(convertTimeUnit(v.durationTotal, 'ms', 'm')),
            yarnLength: formatNumber(v.yarnLength)
          }))

          detailGridOptions.data = res.detail.map((v) => ({
            ...v,
            dateTimeStr: splitTsIdToTime(v.tsId) + v.shiftName,
            efcRun: formatNumber(v.efcRun),
            // classLength: formatNumber(v.classLength, 0),
            actualYarnWeight: formatNumber(v.actualYarnWeight, 1),
            // jointTimeRound: formatNumber(v.jointTimeRound, 0),
            stopTime: formatDate(v.stopTime),
            stopTimeAvg: formatDate(v.stopTimeAvg),
            warningCnt: v.warningCnt,
            durationTotal: formatNumber(convertTimeUnit(v.durationTotal, 'ms', 'm')),
            yarnLength: formatNumber(v.yarnLength)
          }))
        })
      }
    } catch (err) {
      console.log(err)
    } finally {
      hideTablesLoading()
    }
  }

  const formRef = ref<BasicFormInstance<FormV0>>()
  const formOptions = reactive<BasicFormProps<FormV0>>({
    data: {} as FormV0,
    titleWidth: 60,
    items: [
      {
        field: 'quYuValue',
        title: '区域',
        visibleMethod: () => props.isQuYu,
        itemRender: {
          name: 'ElSelect',
          options: computed(() => quYuOptions.value) as unknown as LabelValueOption[],
          props: { style: 'width: 100px' },
          events: {
            change: () => {
              getTsIdSelect()
              getEquipmentList()
            }
          }
        }
      },
      {
        field: 'gongXuId',
        itemRender: {
          name: 'ElSelect',
          options: computed(() => gongXuOptions.value) as unknown as LabelValueOption[],
          props: { style: 'width: 100px' },
          events: {
            change: () => {
              handleGongXuChange()
            }
          }
        }
      },
      {
        field: 'tsIdSelect',
        itemRender: {
          name: 'ShiftSchedulePicker',
          props: {
            shiftOptions: computed(() => shiftOptions.value) as unknown as LabelValueOption[]
          }
        }
      },
      {
        field: 'equipmentList',
        title: t('custom.机台'),
        itemRender: {
          name: 'SelectModal',
          props: {
            modalConfig: {
              title: t('system.列表选择', { name: t('custom.机台') }),
              options: computed(() => equipmentOptions.value)
            }
          }
        }
      },
      {
        field: 'form-actions',
        itemRender: {
          name: 'ActionButtons',
          children: [{ name: 'search' }]
        }
      }
    ]
  })

  const statisticsGridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: '品种统计表',
      isCustom: true,
      isExport: true,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `personAdmin-jiXiaoKaoHao-JiTaiView-statistics`, // id用于缓存,务必配置
    maxHeight: 480,
    columns: columns['细纱']['equipment']['statisticsColumns'],
    toolbarConfig: {}, // 工具栏
    exportConfig: {
      filename: '绩效考核_按机台'
    },
    showFooter: true,
    footerMethod: calcFooter({
      ...sumFields.reduce((acc, field: string) => {
        acc[field] = 'sum'
        return acc
      }, {}),
      materialName: {
        formatter: () => '合计'
      }
    })
  })

  const statisticsByMaterialGridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: '机台品种统计表',
      isCustom: true,
      isExport: false,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `personAdmin-jiXiaoKaoHao-JiTaiView-statisticsByMaterialMachine`, // id用于缓存,务必配置
    maxHeight: 480,
    columns: columns['细纱']['equipment']['statisticsByMaterialColumns'],
    toolbarConfig: {} // 工具栏
  })

  const detailGridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: '班次详细表',
      isCustom: true,
      isExport: false,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `personAdmin-jiXiaoKaoHao-JiTaiView-detail`, // id用于缓存,务必配置
    maxHeight: 480,
    columns: columns['细纱']['equipment']['detailColumns'],
    toolbarConfig: {} // 工具栏
  })

  onMounted(async () => {
    await getGongXuBuDaiFuJi()
    // 有区域先拿区域 再用区域选项第一个去拿机台和班次
    if (props.isQuYu) {
      quYuOptions.value = await getQuYuOptions()
      formOptions.data!.quYuValue = quYuOptions.value[0].value
    }
    await getEquipmentList()
    await getTsIdSelect()
  })
</script>

<style lang="scss" scoped></style>
